package com.dayatang.android.Activity;

import java.util.List;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import com.dayatang.android.Db.DictionaryServiceDb;
import com.dayatang.android.Model.Dictionary;
import com.dayatang.android.config.Config;

public class ProjectAdvancedSearchActivity extends FootCommonActivity {

	private DictionaryServiceDb dictionaryServiceDb;
	private ArrayAdapter<CharSequence> adapter;
	private Spinner constructionDepartmentSpinner,projectTypeSpinner,ownerinfoSpinner,supervisorinfoSpinner,designerinfoSpinner;
	
	private String ownerOrgId;
	private String supervisorOrgId;
	private String designerOrgId;
	private String responsibleOrgId;
	private String projectType;
	
	private String[] dictionary;
	private String[] dictionaryDivisionOrgId;
	private String[] dictionaryOwnerOrgId;
	private String[] dictionarySupervisorOrgId;
	private String[] dictionaryDesignerOrgId;
	private String[] projectTypeId;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		dictionaryServiceDb = new DictionaryServiceDb(this);
		
		AlabSetContentView(R.layout.project_advanced_search_activity);
		AlabSetBarTitleText(getString(R.string.advanced_project_search_title));
		
		InitSpinner();
	}
	
	private void InitSpinner() {
		constructionDepartmentSpinner = (Spinner) findViewById(R.id.advanced_search_construction_department_spinner);
		InitSpinnerData(constructionDepartmentSpinner,"divisionOrg");
		
		projectTypeSpinner = (Spinner) findViewById(R.id.advanced_search_project_type_spinner);
		InitSpinnerData(projectTypeSpinner,"projectType");
		
		ownerinfoSpinner = (Spinner) findViewById(R.id.advanced_search_ownerinfo_spinner);
		InitSpinnerData(ownerinfoSpinner,"ownerOrg");

		supervisorinfoSpinner = (Spinner) findViewById(R.id.advanced_search_supervisorinfo_spinner);
		InitSpinnerData(supervisorinfoSpinner,"supervisorOrg");

		designerinfoSpinner = (Spinner) findViewById(R.id.advanced_search_designerinfo_spinner);
		InitSpinnerData(designerinfoSpinner,"designerOrg");
		
		InitBtnSearch();
	}
	
	private void InitBtnSearch() {
		((Button) findViewById(R.id.advanced_search_btn)).setOnClickListener(new Button.OnClickListener() {
			public void onClick(View arg0) {
				if (checking()) {
					String url = "ownerOrgId="+ownerOrgId+"&supervisorOrgId="+supervisorOrgId+"&designerOrgId="+designerOrgId+"&responsibleOrgId="+responsibleOrgId+"&projectType="+projectType+"&username="+getUser().getUsername();
					Log.i("123", url);
					Intent intent = new Intent(ProjectAdvancedSearchActivity.this,ProjectListActivity.class);
					intent.putExtra(Config.PROJNAME, "");
					intent.putExtra(Config.URL, url);
					startActivity(intent);
				}
			}
		});
	}
	
	private boolean checking() {
		if (ownerOrgId.equals("0") && supervisorOrgId.equals("0") && designerOrgId.equals("0") && responsibleOrgId.equals("0") && projectType.equals("")) {
			ToastShow(getString(R.string.advanced_search_condition_noNull));
			return false;
		}
		return true;
	}
	
	private void InitSpinnerData(final Spinner spinner ,final String type) {
		
		List<Dictionary> dictionaries = dictionaryServiceDb.getDictionaryByDictionaryType(type);
		
		if (dictionaries.size() == 0) {
			InitData();
			dictionaries = dictionaryServiceDb.getDictionaryByDictionaryType(type);
		} 
		
		if(type.equals("divisionOrg")){
			dictionaryDivisionOrgId = new String[dictionaries.size()+1];
			dictionaryDivisionOrgId[0] = "0";
		}else if(type.equals("ownerOrg")){
			dictionaryOwnerOrgId = new String[dictionaries.size()+1];
			dictionaryOwnerOrgId[0] = "0";
		}else if(type.equals("supervisorOrg")){
			dictionarySupervisorOrgId = new String[dictionaries.size()+1];
			dictionarySupervisorOrgId[0] = "0";
		}else if(type.equals("designerOrg")){
			dictionaryDesignerOrgId = new String[dictionaries.size()+1];
			dictionaryDesignerOrgId[0] = "0";
		}else if(type.equals("projectType")){
			projectTypeId = new String[dictionaries.size()+1];
			projectTypeId[0] = "";
		}
		
		dictionary = new String[dictionaries.size()+1];
		dictionary[0] = "";
		
		for (int i = 0; i < dictionaries.size(); i++) {
			
			dictionary[i+1] = dictionaries.get(i).getName();
			
			if(type.equals("divisionOrg")){
				dictionaryDivisionOrgId[i+1] = dictionaries.get(i).getThisid();
			}else if(type.equals("ownerOrg")){
				dictionaryOwnerOrgId[i+1] = dictionaries.get(i).getThisid();
			}else if(type.equals("supervisorOrg")){
				dictionarySupervisorOrgId[i+1] = dictionaries.get(i).getThisid();
			}else if(type.equals("designerOrg")){
				dictionaryDesignerOrgId[i+1] = dictionaries.get(i).getThisid();
			}else if(type.equals("projectType")){
				projectTypeId[i+1] = dictionaries.get(i).getThisid();
			}
			
		}
		
		adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item,dictionary);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
		
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,   
                    int position, long id) {   
				if (type.equals("divisionOrg")) {
					responsibleOrgId = dictionaryDivisionOrgId[position];
				} else if (type.equals("projectType")) {
					projectType = projectTypeId[position];
				} else if(type.equals("ownerOrg")) {
					ownerOrgId = dictionaryOwnerOrgId[position];
				} else if(type.equals("supervisorOrg")) {
					supervisorOrgId = dictionarySupervisorOrgId[position];
				} else if(type.equals("designerOrg")) {
					designerOrgId = dictionaryDesignerOrgId[position];
				}
			}
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		});
	}
	
	private void InitData() {
		try {
			dictionaryServiceDb.delDictionaryByType(null);
			String url = getServerAddress() + "/remote/init-search-data.action";
			String data = getHttpData(this, url);
			if (data != null) {
				JSONObject jsonObject = new JSONObject(data);
				
				JSONArray jsonArray = jsonObject.getJSONArray("divisionOrg");
				saveDibByJsonArray(jsonArray,"divisionOrg");
				
				JSONArray jsonArray1 = jsonObject.getJSONArray("projectType");
				saveDibByJsonArray(jsonArray1,"projectType");
	
				JSONArray jsonArray2 = jsonObject.getJSONArray("ownerOrg");
				saveDibByJsonArray(jsonArray2,"ownerOrg");
	
				JSONArray jsonArray3 = jsonObject.getJSONArray("supervisorOrg");
				saveDibByJsonArray(jsonArray3,"supervisorOrg");
	
				JSONArray jsonArray4 = jsonObject.getJSONArray("designerOrg");
				saveDibByJsonArray(jsonArray4,"designerOrg");
			} else {
				ToastShow(getString(R.string.data_analysis_error));
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	private void saveDibByJsonArray(JSONArray jsonArray,String type) throws JSONException {
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			Dictionary dictionary = new Dictionary();
			dictionary.setName(jsonObject.getString("name"));
			dictionary.setThisid(jsonObject.getString("id"));
			dictionary.setType(type);
			dictionaryServiceDb.save(dictionary);
		}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			this.finish();
			overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0,INIT_DATA_ID,0,getString(R.string.omenu_update_init_data));
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case INIT_DATA_ID:
				dictionaryServiceDb.delDictionaryByType(new String[]{"divisionOrg"});
				dictionaryServiceDb.delDictionaryByType(new String[]{"projectType"});
				dictionaryServiceDb.delDictionaryByType(new String[]{"ownerOrg"});
				dictionaryServiceDb.delDictionaryByType(new String[]{"supervisorOrg"});
				dictionaryServiceDb.delDictionaryByType(new String[]{"designerOrg"});
				InitData();
				startActivity(new Intent(this,ProjectAdvancedSearchActivity.class));
				finish();
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

	
}
